<template>
  <div class="quick_reply_sort_set">
    <!-- 分类头部 -->
    <div class="left-head clearfix">
      <el-checkbox class="check_all" :indeterminate="isIndeterminate" v-model="checkAll" @change="sortCheck('all')"></el-checkbox>
      <span class="all_sort" @click="allSort">{{$t('webchat.allCategory')}}</span>
      <div class="delete_sort_btn" v-show="isIndeterminate || checkAll" @click="removeDomain('all')"><span class = "iconfont icon-qiapianshangdeguanbi"></span>{{$t('webchat.moreDel')}}</div>
      <div class="add_sort_btn" @click="exportSort" v-show="isIndeterminate || checkAll" :title="$t('configLazyLoad.channel.globalTip1')"><span class = "iconfont icon-daochu"></span>{{$t('public.export')}}</div>
      <div class="add_sort_btn" @click="addSort"><span class = "iconfont icon-zhankai"></span>{{$t('public.add')}}</div>
    </div>
    <el-form :model="sortObj" ref="sortObj" class="drag_list_box">
      <!-- 快捷回复分类列表 -->
      <draggable :list="sortObj.dragList" :options="{handle:'.draggable_handle'}" @start="drag=true" @end="dragEnd">
        <el-form-item
                v-for="(domain, index) in sortObj.dragList"
                class="drag_list_li"
                :class="domain.selected ? 'active_li' : ''">
          <!-- 分类拖拽按钮 -->
          <span class="iconfont icon-shunxutuozhuai" v-show="editindex !== -1"></span>
          <span class="draggable_handle iconfont icon-shunxutuozhuai" v-show="editindex === -1"></span>
          <!-- 批量选中复选框 -->
          <el-checkbox class="sort_checkbox" v-model="domain.checked" @change="sortCheck" v-show="editindex !== index"></el-checkbox>
          <!-- 分类名称 -->
          <span class="ellipsis content_span" v-show="editindex !== index" @click.prevent="sortLiClick(index)" :title="domain.name">{{domain.name}}</span>
          <!-- 编辑分类按钮 -->
          <div class="fr edit_btn">
            <span class="span_btn iconfont icon-beizhu" type="text" size="mini" @click.prevent="editDomain(index)" v-show="editindex !== index"></span>
            <span class="span_btn iconfont icon-guanbi1" type="text" size="mini" @click.prevent="removeDomain(index)" v-show="editindex !== index"></span>
          </div>
          <!-- 编辑快捷回复分类输入框 -->
          <el-input
                  v-show="editindex === index"
                  class="domain_edit_input"
                  :autosize="true"
                  resize="none"
                  size="mini"
                  :placeholder="$t('webchat.pleaseEnterCategoryName')"
                  v-model.trim="editCon">
          </el-input>
          <!-- 编辑||添加的确定&&取消按钮 -->
          <div class="todo_box fr" v-show="editindex === index">
            <span class="iconfont icon-xuanzhong" @click="saveEdit(domain, index)"></span>
            <span class="iconfont icon-qiapianshangdeguanbi" @click="cancelEdit(domain, index)"></span>
          </div>
        </el-form-item>
      </draggable>
    </el-form>
  </div>
</template>
<script>
  import draggable from 'vuedraggable'
  import {deepClone} from '@utils/m7Utils'
  import * as gtypes from '@/store/mutation-types'
  import { orderBy } from 'lodash'
  import bus from '@/store/eventBus'
  export default {
    name: 'quickReplySort',
    data () {
      return {
        oldEditCon: '',         //  暂存分类名称
        editindex: -1,          //  当前编辑的分类的index
        editCon: '',            //  添加||编辑分类时的数据
        checkedCount: 0,        //  当前选中的分类条数
        checkAll: false,        //  是否全选
        isIndeterminate: false, //  是否部分选中
        sortObj: {              //  所有分类数据
          dragList: []
        }
      }
    },
    props: {
      //  刷新分类的随机数
      sortRandom: {
        type: Number,
        default: 0
      },
//      当前选中的分类
      currentSort: {
        type: String,
        default: ''
      },
//      操作类型，是公共快捷回复还是自定义快捷回复
      dataType: {
        type: String,
        default: ''
      }
    },
    watch: {
//      监听分类随机数，刷新分类
      sortRandom () {
        this.initSortList()
      }
    },
    components: {
      draggable,
      bus
    },
    methods: {
//      编辑分类
      editDomain (index) {
        if (this.editindex >= 0) {
          this.$message.error(this.$t('webchat.pleaseSave'))
          return
        }
        this.oldEditCon = deepClone(this.sortObj.dragList[index].name)
        this.editCon = this.oldEditCon
        this.editindex = index
      },
//      删除分类
      removeDomain (index) {
        if (this.editindex >= 0) {
          this.$message.error(this.$t('webchat.pleaseSave'))
          return
        }
        let self = this
        self.$confirm(self.$t('webchat.sureDeleteAllSort'), self.$t('public.tip'), {
          confirmButtonText: self.$t('public.confirm'),
          cancelButtonText: self.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          let idArr = []
          let isChecked = false
//          批量删除分类
          if (index === 'all') {
            self.sortObj.dragList.forEach((item) => {
              if (item.checked) {
                idArr.push(item._id)
                if (item.selected) {
                  isChecked = true
                }
              }
            })
          } else {
//            单个删除分类
            idArr.push(self.sortObj.dragList[index]._id)
            if (self.sortObj.dragList[index].selected) {
              isChecked = true
            }
          }
          let data = {
            ids: idArr,
            moduleType: 'webchat'
          }
//          删除分类的时候判断是自定义快捷回复还是公共快捷回复
          let actionData = 'newDeleteQuickReplyTag'
          if (self.dataType === 'customize') {
            actionData = 'newDeleteAgentQuickReplyTag'
          }
          self.$store.dispatch(actionData, data).then(res => {
            if (res && res.success) {
              if (isChecked) {
                bus.$emit('sortActive', {
                  _id: '',
                  name: '',
                  dataType: self.dataType
                })
              } else if (index === 'all') {
                bus.$emit('removeAllSort', {dataType: self.dataType})
              }
              self.initSortList()
              self.$message({
                message: this.$t('configLazyLoad.channel.globalTip2'),
                type: 'success'
              })
            }
          }) 
        }).catch(() => {})
      },
//      批量选中快捷回复
      sortCheck (val) {
//        val不是'all'代表是选中了单个的分类，选中单个的值是true或者false
        if (typeof val !== undefined && typeof val !== 'string') {
          if (val) {
            this.checkedCount += 1
          } else {
            this.checkedCount -= 1
          }
          if (this.checkedCount < 0) {
            this.checkedCount = 0
          }
          this.checkAll = this.checkedCount === this.sortObj.dragList.length
          this.isIndeterminate = this.checkedCount > 0 && this.checkedCount < this.sortObj.dragList.length
        } else {
//          点击全部选择按钮
          let checkFlag = false
//          如果此时所有选项全部选中，则取消全部选中
          if (this.checkedCount === this.sortObj.dragList.length) {
            this.checkedCount = 0
            this.checkAll = false
            checkFlag = false
          } else {
//          如果此时没有全部选中，则进行全部选中操作
            this.checkedCount = this.sortObj.dragList.length
            this.checkAll = true
            checkFlag = true
          }
          this.sortObj.dragList.forEach((item) => {
            this.$set(item, 'checked', checkFlag)
          })
          this.isIndeterminate = this.checkedCount > 0 && this.checkedCount < this.sortObj.dragList.length
        }
      },
//      选中当前分类
      sortLiClick (curIndex) {
        if (this.editindex >= 0) {
          this.$message.error(this.$t('webchat.pleaseSave'))
          return
        }
        this.sortObj.dragList.forEach((item, index) => {
          if (index === curIndex) {
            this.$set(item, 'selected', true)
          } else {
            this.$set(item, 'selected', false)
          }
        })
        this.$set(this.sortObj.dragList[curIndex], 'selected', true)
        bus.$emit('sortActive', {
          _id: this.sortObj.dragList[curIndex]._id,
          name: this.sortObj.dragList[curIndex].name,
          dataType: this.dataType
        })
      },
//      点击全部分类按钮
      allSort () {
        this.sortObj.dragList.forEach((item) => {
          this.$set(item, 'selected', false)
        })
        this.initSortList()
        bus.$emit('sortActive', {_id: '', name: '', dataType: this.dataType})
      },
//      保存类别
      saveEdit (dataObj, index) {
//        保存类别的修改操作
        let self = this
        if (!self.editCon) {
          self.$message.error(this.$t('webchat.sortNameNotEmpty'))
          return
        }
//        存在_id即为修改操作
        if (dataObj._id) {
          let data = {
            _id: dataObj._id,
            name: self.editCon,
            moduleType: 'webchat'
          }
          let actionData = 'newUpdateQuickReplyTag'
          if (self.dataType === 'customize') {
            actionData = 'newUpdateAgentQuickReplyTag'
          }
          self.$store.dispatch(actionData, data).then(res => {
            if (res && res.success) {
              if (self.sortObj.dragList[self.editindex].selected) {
                bus.$emit('editSelected', {data: self.editCon, dataType: self.dataType})
              }
              self.$set(self.sortObj.dragList[index], 'name', self.editCon)
              self.oldEditCon = ''
              self.editCon = ''
              self.editindex = -1
              this.initSortList()
            }
          })
        } else {
//          添加类别
          let data = {
            sort: this.sortObj.dragList.length - 1,
            name: deepClone(this.editCon),
            moduleType: 'webchat'
          }
          let actionData = 'newAddQuickReplyTag'
          if (this.dataType === 'customize') {
            actionData = 'newAddAgentQuickReplyTag'
          }
          this.$store.dispatch(actionData, data).then(res => {
            if (res && res.success) {
              this.$set(this.sortObj.dragList[index], 'name', this.editCon)
              this.editindex = -1
              this.initSortList()
            } else {
              this.$store.commit(gtypes.SET_ERROR, 'message.' + res.message)
            }
          })
        }
      },
//      拖动分类
      dragEnd (val) {
        let self = this
        let active = 'newBatchUpdateQuickReplyTag'
        if (self.dataType === 'customize') {
          active = 'newBatchUpdateAgentQuickReplyTag'
        }
        let _id = self.sortObj.dragList[val.newIndex]._id
        self.$store.dispatch(active, {_id: _id, sort: val.newIndex}).then(res => {
          if (res && res.success) {
            self.$message.success(this.$t('business.updateSuccess'))
          }
          self.initSortList()
        })
      },
//      加载所有快捷回复分类
      initSortList () {
        let self = this
        let data = {
          moduleType: 'webchat'
        }
//        区分是自定义快捷回复还是公共快捷回复
        let active = 'newQueryQuickReplyTag'
        if (self.dataType === 'customize') {
          active = 'newQueryAgentQuickReplyTag'
        }
        self.$store.dispatch(active, data).then(res => {
          if (res && res.success) {
            let resData = deepClone(res.data)
            resData.forEach((item) => {
              if (typeof item.sort === 'undefined') {
                self.$set(item, 'sort', 0)
              }
              self.$set(item, 'checked', false)
              if (self.currentSort === item._id) {
                self.$set(item, 'selected', true)
              } else {
                self.$set(item, 'selected', false)
              }
            })
            self.checkedCount = 0
            self.checkAll = false
            self.isIndeterminate = false
            self.sortObj.dragList = self.queueSort(resData)
            bus.$emit('sortChange', {data: res.data, dataType: self.dataType})
            self.editCon = ''
            self.editindex = -1
            if (self.dataType === 'customize') {
              bus.$emit('refreshAgentReply')
            }
          }
        })
      },
//      梳理分类，让分类按照sort排序，若是相同的sort，则按照updateTime排序
      queueSort (data) {
        data = orderBy(data, [(o) => {
          let aa = o['sort'] || -1
          return aa
        }, (o) => {
          let aa = o['updatedTime'] || 0
          return aa
        }], ['asc', 'desc'])
        return data
      },
//      取消编辑||添加分类
      cancelEdit (obj, index) {
        this.editindex = -1
        this.editCon = ''
        if (obj._id) {
          this.oldEditCon = ''
        } else {
          this.sortObj.dragList.splice(index, 1)
        }
      },
//      添加分类
      addSort () {
        let self = this
        if (self.editindex >= 0) {
          self.$message.error(this.$t('webchat.pleaseSave'))
          return
        }
        self.sortObj.dragList.push({
          name: '',
          moduleType: 'webchat'
        })
        self.editindex = self.sortObj.dragList.length - 1
        self.$nextTick(function () {
          let dom = self.$el.getElementsByClassName('drag_list_box')[0]
          dom.scrollTop = dom.scrollHeight
        })
      },
//      导出分类
      exportSort () {
        let list = deepClone(this.sortObj.dragList)
        let dataObj = {
          exportAll: true
        }
        if (!this.checkAll && this.checkedCount > 0) {
          let arr = []
          list.forEach((item) => {
            if (item.checked) {
              arr.push(item._id)
            }
          })
          dataObj = {
            tagIdList: arr
          }
        }
        let data = {
          Method: this.dataType === 'customize' ? 'exportQuickReplyAgent' : 'exportQuickReply',
          Query: dataObj
        }
        this.$store.dispatch('exportQuickReply', data).then(res => {
          if (res.success) {
//            this.initSortList()
          }
        })
      }
    },
    beforeMount () {
      this.initSortList()
    }
  }
</script>
<style lang="stylus" scoped="">
  @import "../../../../../assets/common.styl"
  .quick_reply_sort_set
    height 100%
  .left-head
    line-height 44px
    border-bottom 1px solid #e7e7eb
    .iconfont
      line-height 44px
    .all_sort
      color $cf-gray3
      margin 0 10px 0 0
      cursor pointer
    .add_sort_btn,.delete_sort_btn
      display inline-block
      float right
      margin-right 10px
      cursor pointer
      color $c-main
      font-size 12px
    .delete_sort_btn
      color $c-pink
  .drag_list_box
    height calc(100% - 48px)
    overflow-y auto
    .drag_list_li
      padding 6px 6px 6px 0
      margin 0
      &.active_li
        .edit_btn
          display inline-block
      &:hover
        background #E5F1FF
        .edit_btn
          display inline-block
      .draggable_handle
        display inline-block
        cursor move
      .sort_checkbox
        margin-right 4px
      .content_span
        overflow hidden
        display inline-block
        width calc(100% - 80px)
        vertical-align bottom
        cursor pointer
      .edit_btn
        display none
        height 20px
        .iconfont
          font-size 16px
      .span_btn
        color $c-main
        cursor pointer
        vertical-align middle
      .span_btn:nth-child(2)
        color $c-pink
        margin-left 6px
  .icon-shunxutuozhuai
    margin 0 2px
    color $c-affix
    display inline-block
  .todo_box
    display inline-block
    line-height 30px
    .iconfont
      font-size 16px
      color $c-main
      cursor pointer
    .iconfont:nth-child(2)
      color $c-pink
      margin-left 6px
  .domain_edit_input
    width calc(100% - 66px)
    padding 0
  .active_li
    background #E5F1FF
  .check_all
    margin 0 8px
  .el-button
    padding 0
    border none
    margin-left 8px
  .iconfont
    font-size 12px
  .icon-qiapianshangdeguanbi
    color $c-pink
</style>
